import random
from utils.ytx_sdk.sendSMS import CCP
from rest_framework.response import Response
from django.shortcuts import render
from rest_framework import serializers
# Create your views here.
from django_redis import get_redis_connection
from rest_framework.views import APIView
from celery_tasks.sms.tasks import sms_send
class SMSCodeView(APIView):
#     判断是否用序列化器（输出是字典不用序列化器
# 验证ｍｏｂｉｌ用的正则，不需要保存，不用反序列化器）
    def get(self,request,mobile):
        # 链接ｒｅｄｉｓ，长久保存用ｍｙｓｑｌ，时间短用ｒｅｄｉｓ
        redis_cli = get_redis_connection('verify_code')
        # 1.检查是否在60s内有发送纪录,看是否在ｒｅｄｉｓ里，过期时间６０
        sms_flag =redis_cli.get('sms_flag_'+mobile)
        if sms_flag:
            raise serializers.ValidationError('请稍候再发送短信验证码')
        # 2.生气短信验证码
        sms_code = str(random.randint(100000,999999))
        # 3.保存短信验证码与发送纪录
        # redis_cli.setex('sms_code_' + mobile, 300, sms_code)
        # # 存发送标记，60秒
        # redis_cli.setex('sms_flag_' + mobile, 60, 1)
#         优化ｒｅｄｉｓ交互,管道ｐｉｐｅｌｉｎｅ
        redis_pl = redis_cli.pipeline()
        redis_pl.setex('sms_code_' + mobile, 300, sms_code)
        redis_pl.setex('sms_flag_' + mobile, 60, 1)
        redis_pl.execute()
#         发送短信
#         CCP.sendTemplateSMS(mobile,sms_code,5,1)
        print(sms_code)
        sms_send.delay(mobile, sms_code, 5, 1)


        return Response({'messagi':'ok'})




